/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年12月2日
 */
package com.massyframework.beanskin.graphql;

import static graphql.schema.GraphQLScalarType.newScalar;
import java.util.stream.Collectors;

import graphql.Assert;
import graphql.language.ArrayValue;
import graphql.language.BooleanValue;
import graphql.language.EnumValue;
import graphql.language.FloatValue;
import graphql.language.IntValue;
import graphql.language.NullValue;
import graphql.language.ObjectField;
import graphql.language.ObjectValue;
import graphql.language.StringValue;
import graphql.schema.Coercing;
import graphql.schema.CoercingParseLiteralException;
import graphql.schema.CoercingParseValueException;
import graphql.schema.CoercingSerializeException;
import graphql.schema.GraphQLScalarType;

/**
 * @author huangkh
 *
 */
public final class _Any {
	public static final String typeName = "_Any";

	@SuppressWarnings("rawtypes")
	static final Coercing defaultCoercing = new Coercing() {
		@Override
		public Object serialize(Object dataFetcherResult) throws CoercingSerializeException {
			return dataFetcherResult;
		}

		@Override
		public Object parseValue(Object input) throws CoercingParseValueException {
			return input;
		}

		@Override
		public Object parseLiteral(Object input) throws CoercingParseLiteralException {
			if (input instanceof NullValue) {
				return null;
			} else if (input instanceof FloatValue) {
				return ((FloatValue) input).getValue();
			} else if (input instanceof StringValue) {
				return ((StringValue) input).getValue();
			} else if (input instanceof IntValue) {
				return ((IntValue) input).getValue();
			} else if (input instanceof BooleanValue) {
				return ((BooleanValue) input).isValue();
			} else if (input instanceof EnumValue) {
				return ((EnumValue) input).getName();
			} else if (input instanceof ArrayValue) {
				return ((ArrayValue) input).getValues().stream().map(this::parseLiteral).collect(Collectors.toList());
			} else if (input instanceof ObjectValue) {
				return ((ObjectValue) input).getObjectFields().stream()
						.collect(Collectors.toMap(ObjectField::getName, f -> parseLiteral(f.getValue())));
			}
			return Assert.assertShouldNeverHappen();
		}
	};

	private _Any() {
	}

	@SuppressWarnings("rawtypes")
	static GraphQLScalarType type(Coercing coercing) {
		return newScalar().name(typeName).coercing(coercing).build();
	}
}
